import {
  EditOutlined,
  CloudDownloadOutlined,
  PlusOutlined,
  DeleteOutlined
} from '@ant-design/icons'
import 'antd/dist/antd.css'
// @ts-ignore
import flag from '../assets/image/new_icon.png'
// @ts-ignore
import setting from '../assets/image/setting.png'
// @ts-ignore
import start from '../assets/image/start.png'
// @ts-ignore
import edit from '../assets/image/edit.png'
import { history } from 'umi'
import { Avatar, Card, Tooltip, List, Button, Modal, message,Spin,notification } from 'antd'
import React, { FC, useEffect, useRef, useState } from 'react'
import { ListItemDataType } from './data.d'
// @ts-ignore
import styles from './style.less'
import { DatabaseOutlined, FolderOpenOutlined, LoadingOutlined } from '@ant-design/icons/lib'
import { PageContainer } from '@ant-design/pro-layout'
import { changeSize } from '@utils/electron'
import { deleteProject, genProject, getProjectList } from '@/services/project'
import Tag from 'antd/es/tag'
import LocalPathForm from '@pages/components/LocalPathForm'
const ipc = require('electron').ipcRenderer

interface ApplicationsProps {
  dispatch: any;
  loading: boolean;
}

const ColorList = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae', '#1890ff']

const CardInfo: React.FC<{
  type: React.ReactNode;
  description: any;
}> = ({ type, description }) => (
  <div className={styles.cardInfo}>
    <div>
      <p>应用类型</p>
      <Tag color="blue">{type === 'simple' ? '单应用' : '微服务'}</Tag>
    </div>
    <div>
      <p>应用介绍</p>
      <Tag color="volcano">{description.length > 7 ? `${description.slice(0, 7)}...` : description}</Tag>
    </div>
  </div>
)


export const Applications: FC<ApplicationsProps> = (props) => {
  const {
    loading
  } = props


  const [projectList, setProjectList] = useState<any>([])
  const [visible, setVisible] = useState<boolean>(false)
  const [proDetail, setProDetail] = useState<any>({})
  const [path, setPath] = useState<any>('')
  const [asyncLoading, setAsyncLoading] = useState<boolean>(false)

  useEffect(() => {
    changeSize(1250, 860, '首页')
    queryDate()
  }, [])

  const queryDate = () => {
    getProjectList().then((res: any) => {
      if (res.code == 10000) {
        const list = [{}, ...res.data]
        setProjectList(list)
      }else {
        notification.error({
          message: `数据请求错误`,
          description: res.msg,
          duration:0
        });
      }
    })
  }

  const deletePro = (id: any) => {
    Modal.confirm({
      title: '确认',
      content: '是否确认删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        deleteProject({ 'id': id }).then((res) => {
          if (res.code === 10000) {
            message.success('删除成功')
            queryDate()
          }
        })
      }
    })
  }

  const asyncProject = (flag: boolean, item: any) => {

    if (!flag) {
      setVisible(flag)
      setProDetail({});
      return
    }
    setPath(item.local_path);
    setProDetail(item)

    setVisible(true);
  }

  const handleOk = (val:any) => {
    setVisible(false)
    setPath(val.local_path)
    setAsyncLoading(true)
    // 调取生成项目的方法
    genProject({ id: proDetail.id, localPath: val.local_path, proType: proDetail.pro_type }).then(res => {
      if (res.code === 10000) {
        setAsyncLoading(false);
        message.success('项目生成成功！');
      }
    })
  }

  ipc.on('router', function (event:any, arg:any) {
    history.push(`${arg}`)
  })

  const extraContent = (
    <div style={{ textAlign: 'center', marginBottom: 40 }}>
      <img alt="logo" src={flag} width={130}/>
      <div style={{ fontSize: 40, fontWeight: 600 }}>AutoCode</div>
    </div>
  )

  const content = (
    <>
      {extraContent}
      <div className={styles.pageHeaderContent}>
        <p>
          欢迎使用AutoCode代码生成工具，使用本产品可让你专注于代码逻辑，不再为简单的增删改查而苦恼。
        </p>
        <div className={styles.contentLink}>
          <a>
            <img alt="" src={start}/>{' '}
            快速开始
          </a>
          <a onClick={() => history.push(`/databaseConfig`)}>
            <img alt="" src={edit}/>{' '}
            数据库管理
          </a>
          <a onClick={() => history.push('/appConfig')}>
            <img alt="" src={setting}/>{' '}
            系统配置
          </a>
        </div>
      </div>
    </>
  )

  const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;

  return (
    <Spin style={{top:400}} indicator={antIcon} size='large' tip="项目正在生成中,请稍等..." spinning={asyncLoading}>
      <PageContainer content={content}>
        <div className={styles.filterCardList}>
          <List<ListItemDataType>
            rowKey="id"
            grid={{
              gutter: 16,
              xs: 1,
              sm: 2,
              md: 3,
              lg: 3,
              xl: 4,
              xxl: 5
            }}
            loading={loading}
            dataSource={projectList}
            renderItem={(item: any, index: number) => {
              if (item && item.id) {
                const color = ColorList[index % 5]
                return <List.Item key={item.id}>
                  <Card
                    hoverable
                    bodyStyle={{ paddingBottom: 20 }}
                    actions={[
                      <Tooltip key="open" title="打开">
                        <FolderOpenOutlined
                          onClick={() => history.push(`/projectDetail?projectId=${item.id}&projectName=${item.name}&comment=${item.description}`)}/>
                      </Tooltip>,
                      <Tooltip key="edit" title="编辑">
                        <EditOutlined onClick={() => history.push(`/handleProject?projectId=${item.id}`)}/>
                      </Tooltip>,
                      <Tooltip title="删除项目" key="delete">
                        <DeleteOutlined onClick={() => deletePro(item.id)}/>
                      </Tooltip>,
                      <Tooltip title="生成项目" key="share">
                        <CloudDownloadOutlined onClick={() => asyncProject(true, item)}/>
                      </Tooltip>
                    ]}
                  >
                    <Card.Meta avatar={<Avatar size={28}
                                               style={{ backgroundColor: color }}>{item.name?.substr(0, 1) || '空'}</Avatar>}
                               title={item.name}/>
                    <div className={styles.cardItemContent}>
                      <CardInfo
                        type={item.pro_type}
                        description={item.description}
                      />
                    </div>
                  </Card>
                </List.Item>
              }
              return <List.Item onClick={() => history.push('/handleProject')}>
                <Button type="dashed" className={styles.newButton}>
                  <PlusOutlined/> 新建项目
                </Button>
              </List.Item>
            }
            }
          />
        </div>
        {visible && <LocalPathForm  asyncProject={asyncProject} handleOk={handleOk} visible={visible} localPath={path}/>}
      </PageContainer>
    </Spin>
  )
}

export default Applications
